<?php
namespace common\queue;

use common\models\CacheKeys;
use common\models\redPacket\RedPacketLog;
use common\models\Status;
use common\models\userFund\UserMoneyLog;
use yii\base\Exception;
use yii\queue\Job;
use Yii;

class RedPacket extends \common\models\redPacket\RedPacket implements Job {

    public $data = [];
    public $redis;
    public function __construct($args)
    {
        parent::__construct();
        $this->data = $args;
        $this->redis = Yii::$app->redis;
    }

    public function execute($queue)
    {
        $redPacketLogInfo = $this->data['redPacketLog'];
        $redPacketInfo = $this->data['redPacket'];
        $userInfoArray = $this->data['user'];
        $surplusNum = $this->data['num'];
//        file_put_contents('/tmp/redpacket_receive.txt',"红包信息".date('Y-m-d H:i:s')."\n",FILE_APPEND);
//        file_put_contents('/tmp/redpacket_receive.txt',json_encode($redPacketInfo,true),FILE_APPEND);
//        file_put_contents('/tmp/redpacket_receive.txt',"队列信息".date('Y-m-d H:i:s')."\n",FILE_APPEND);
//        file_put_contents('/tmp/redpacket_receive.txt',json_encode($this->data,true),FILE_APPEND);
        $trans = static::getDb()->beginTransaction();
        try {

            //红包记录 红包 收入明细 用户余额
            $updateRedPacketLog['receive_user_id'] = $userInfoArray['id'];
            $updateRedPacketLog['receive_user_code'] = $userInfoArray['user_code'];
            $updateRedPacketLog['receive_user_tx_code'] = $userInfoArray['tx_code'];
            $updateRedPacketLog['receive_user_phone'] = $userInfoArray['login_name'];
            $updateRedPacketLog['receive_user_nick_name'] = $userInfoArray['nick_name'];
            $updateRedPacketLog['receive_user_face'] = $userInfoArray['user_face'];
            $updateRedPacketLog['status'] = Status::RED_PACKET_DONE;
            $updateRedPacketLog['finish_time'] = date('Y-m-d H:i:s');


            if ($updateRedPacketLog) {
                $res = RedPacketLog::updateData($updateRedPacketLog,['id' => $redPacketLogInfo['id']]);
                if ($res === false) {
                    throw new Exception('红包记录更新失败，红包id:'.$redPacketInfo['id']);
                }
            }

            $updateRedPack = [];
            static::updateAllCounters(['receive_num' => 1],['id' => $redPacketInfo['id']]);
            $surplusNum = $this->redis->llen(CacheKeys::IM_RED_PACKET_WAIT_LIST.$redPacketInfo['id']);
            if ($surplusNum == 0 ) {
                $redPacketInfo['status'] = Status::RED_PACKET_DONE;
                $updateRedPack['status'] = Status::RED_PACKET_DONE;
                $updateRedPack['finish_time'] = date('Y-m-d H:i:s');
            }
            if ($updateRedPack) {
                $resRedPacket = static::updateData($updateRedPack,['id' => $redPacketInfo['id']]);
                if ($resRedPacket === false) {
                    throw new Exception('红包信息更新失败,红包id:'.$redPacketInfo['id']);
                }
            }


//            if ($updateRedPack) {
//                $res = RedPacket::updateAllCounters(["receive_num" => 1],['id' => $redPacketInfo['id']]);
//                if (!$res) {
//                    throw new Exception('领取失败');
//                }
//
//                $currPacket = RedPacket::getOneInfoById($redPacketInfo['id'], ["receive_num", "status"]);
//                if ($currPacket['receive_num'] == $redPacketInfo['num'] && $currPacket['status'] == Status::RED_PACKET_WAIT) {
//                    RedPacket::updateData(['status' => Status::RED_PACKET_DONE],['id' => $redPacketInfo['id']]);
//
//                    if ($redPacketInfo['status'] != Status::RED_PACKET_DONE) {
//                        $redPacketInfo['status'] = Status::RED_PACKET_DONE;
//                    }
//                }
//                $redPacketInfo['receive_num'] = $currPacket['receive_num'];


//                $this->data['num'] = $redPacketInfo['num'] - $currPacket['receive_num'];
            $this->data['num'] = $surplusNum;
            $this->data['redPacket'] = $redPacketInfo;

//            }

            // 余额信息
            UserMoneyLog::record(
                $userInfoArray['id'],
                Status::PROP_TYPE_MONEY,
                Status::MONEY_LOG_TYPE_RECEIVE_RED_PACKET,
                $redPacketLogInfo['receive_money'],
                Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_RECEIVE_RED_PACKET] ?? '',
                '领取红包',
                $redPacketInfo['id']
            );

            $trans->commit();

            $redPacketInfo['receive_num'] = $redPacketInfo['receive_num'] + 1;
            $this->redis->set(CacheKeys::IM_RED_PACKET.$redPacketInfo['id'], json_encode($redPacketInfo));
            $this->redis->expire(CacheKeys::IM_RED_PACKET.$redPacketInfo['id'], 24*60*60);


//            Yii::$app->queue->push(new RedPacketMessage($this->data));

        } catch (\yii\db\Exception $ee) {
            file_put_contents('/tmp/redpacket_receive.txt',"数据库失败:".print_r($ee->getMessage(),true),FILE_APPEND);
//            $this->redis->lpush(CacheKeys::IM_RED_PACKET_WAIT_LIST.$redPacketInfo['id'], json_encode($redPacketLogInfo));
//            $this->redis->srem(CacheKeys::IM_RED_PACKET_LOCK_LIST."{$redPacketInfo['id']}", $userInfoArray['id']);
            $trans->rollBack();
        } catch (Exception $e) {
            file_put_contents('/tmp/redpacket_receive.txt',"失败时间".date('Y-m-d H:i:s')."\n",FILE_APPEND);
            file_put_contents('/tmp/redpacket_receive.txt',"失败原因:".print_r($e->getMessage(),true),FILE_APPEND);
            file_put_contents('/tmp/redpacket_receive.txt',"\n",FILE_APPEND);
//            Yii::$app->queue->push(new RedPacket($this->data));
//            $this->redis->lpush(CacheKeys::IM_RED_PACKET_WAIT_LIST.$redPacketInfo['id'], json_encode($redPacketLogInfo));
//            $this->redis->srem(CacheKeys::IM_RED_PACKET_LOCK_LIST."{$redPacketInfo['id']}", $userInfoArray['id']);
            $trans->rollBack();
            Yii::$app->queue->push(new \common\queue\RedPacket($this->data));
        }
    }


}